package com.yfqy.app.modules.wechat.config;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import javax.net.ssl.SSLContext;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.concurrent.TimeUnit;

@Configuration
public class WechatCertHttpClientConfig {

    @Value("${wechat.pay.wechatpay-cert-path}")
    private String certPath;
    @Value("${wechat.pay.mch-id}")
    private String certPassword;

    @Bean("wechatCertHttpClient")
    public CloseableHttpClient wechatCertHttpClient() {
        try {
            ClassPathResource resource = new ClassPathResource(certPath);
            try (InputStream certStream = resource.getInputStream()) {
                KeyStore keyStore = KeyStore.getInstance("PKCS12");
                keyStore.load(certStream, certPassword.toCharArray());

                SSLContext sslContext = SSLContexts.custom()
                        .loadKeyMaterial(keyStore, certPassword.toCharArray())
                        .build();

                SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                        sslContext,
                        new String[]{"TLSv1", "TLSv1.2", "TLSv1.3"},
                        null,
                        SSLConnectionSocketFactory.getDefaultHostnameVerifier()
                );

                return HttpClients.custom()
                        .setSSLSocketFactory(sslSocketFactory)
                        .setConnectionTimeToLive(30, TimeUnit.SECONDS)
                        .setMaxConnTotal(100)
                        .setMaxConnPerRoute(50)
                        .build();
            }
        } catch (Exception e) {
            throw new RuntimeException("创建微信支付证书HttpClient失败", e);
        }
    }
}
